package cn.xeblog.plugin.action;

import cn.hutool.core.thread.GlobalThreadPool;
import cn.xeblog.plugin.client.ClientConnectConsumer;
import cn.xeblog.plugin.client.XEChatClient;
import cn.xeblog.plugin.handler.AbstractChannelInitializer;
import cn.xeblog.plugin.handler.DefaultChannelInitializer;
import lombok.Data;


/**
 * 连接服务器行为
 *
 * @author anlingyi
 * @date 2021/8/22 9:02 下午
 */
@Data
public class ConnectionAction {
    /**
     * 主机ip
     */
    private String host;
    /**
     * 端口
     */
    private int port;
    /**
     * 单例
     */
    private static ConnectionAction instance = new ConnectionAction();

    private ConnectionAction() {
    }

    /**
     * 获取实例
     *
     * @return
     */
    public static ConnectionAction getInstance() {
        return instance;
    }

    private AbstractChannelInitializer channelInitializer;

    public ConnectionAction(String host, int port, AbstractChannelInitializer channelInitializer) {
        this.host = host;
        this.port = port;
        this.channelInitializer = channelInitializer;
    }

    /**
     * 执行
     *
     * @param consumer 消费式函数接口
     */
    public void exec(ClientConnectConsumer consumer) {
        if (channelInitializer == null) {
            channelInitializer = new DefaultChannelInitializer();
        }
        GlobalThreadPool.execute(() -> XEChatClient.run(host, port, channelInitializer, consumer));
    }

}
